
package com.hd.assistant.web.home.module.screen.order;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.alibaba.fastjson.JSONObject;
import com.hd.assistant.biz.manager.exception.ManagerException;
import com.hd.assistant.dal.dao.orderming.TcOrderDAO;
import com.hd.assistant.dal.dataobject.User;
import com.hd.assistant.dal.dataobject.ordermining.Reports;
import com.hd.assistant.dal.dataobject.ordermining.TcOrder;
import com.hd.assistant.web.common.base.ordermining.BaseTaobaoOrderModule;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.TopatsTradesSoldGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TopatsTradesSoldGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
/**
 *
 * @author Hangding
 */
public class Taobao extends BaseTaobaoOrderModule{
    private final static Logger log = LoggerFactory.getLogger(Taobao.class);
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private HttpSession session;

    @Autowired
    TcOrderDAO tcOrderDAO;
   

    
    public void execute(
    		@Param("code") String code,
    		Context context, Navigator nav) {
    	try{
    		User u = null;
    		if(code != null){
    			generateType(context);
    			u = generateAuth(code);
    			session.setAttribute(TAOBAO_SESSION_KEY, u);
    			nav.redirectToLocation("/order/taobao.htm");
    		}else{
    			u = checkPermision(User.Type_TAOBAO_ORDER, session, context, nav);
    			if(u == null)
    				return;
    		}
    		if(u == null)
				return;
    		context.put("user", u);
			context.put("pindex", 0);
			List<Reports> reports = this.orderMiningManager.getReportsByUserId(u.getUserId(), 1, null, null);
			if(reports != null){
				
			}
			/*this.orderMiningManager.dumpTodayTradesToDB(u, taobaoISVAppManager.getOrderAppKey(), taobaoISVAppManager.getOrderAppSecret(),
					u.getToken());*/
			//this.orderMiningManager.calProfitOfAllDbNoprofitTcOrders(u, null);
			/*orderMiningManager.defaultDumpTradesToDB(u, taobaoISVAppManager.getOrderAppKey(), taobaoISVAppManager.getOrderAppSecret(),
					u.getToken(), 100l);*/
			/*TaobaoClient client=new DefaultTaobaoClient(this.taobaoISVAppManager.getTopUrl(), this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret());
			TopatsTradesSoldGetRequest req=new TopatsTradesSoldGetRequest();
			req.setFields("tid,seller_nick,buyer_nick,payment");
			req.setStartTime("20130515");
			req.setEndTime("20130810");
			TopatsTradesSoldGetResponse response = client.execute(req , u.getToken());
			if(response != null){
				System.out.println(response.getBody());
			}*/
    		/*TaobaoClient client=new DefaultTaobaoClient(this.taobaoISVAppManager.getTopUrl(), this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret());
    		TradesSoldGetRequest reqs=new TradesSoldGetRequest();
    		reqs.setFields("tid,num,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
    		Date dateTime = SimpleDateFormat.getDateTimeInstance().parse("2013-05-01 00:00:00");
    		reqs.setStartCreated(dateTime);
    		Date endTime = SimpleDateFormat.getDateTimeInstance().parse("2013-08-09 23:59:59");
    		reqs.setEndCreated(endTime);
    		
    		reqs.setPageNo(1L);
    		reqs.setPageSize(40L);
    		
    		TradesSoldGetResponse responses = client.execute(reqs , u.getCurrentToken());
    		List<Trade> trades = responses.getTrades();
    		List<TcOrder> orders = new ArrayList<TcOrder>();
    		long begin = System.currentTimeMillis();
    			for(Trade t:trades){
    				TcOrder to = new TcOrder(t);
    				to.setOrdersJson(JSONObject.toJSONString(t.getOrders()));
    				orders.add(to);
    			}
    			long end = System.currentTimeMillis();
    			System.out.println(end-begin);
    			begin = System.currentTimeMillis();
    			for(TcOrder order : orders){
    				this.tcOrderDAO.insertTOrder(order);
    				itemCostCache.put(new Element(order.getTid(), order));
    			}
    		 end = System.currentTimeMillis();
    		System.out.println(end-begin);
    		itemCostCache.put(new Element("171004886", "dddasdsssssssd"));
			itemCostCache.put(new Element("172004886", "dddasdssd"));
			itemCostCache.put(new Element("173004886", "dddasdsd"));
			itemCostCache.put(new Element("171004886", "dddasdsssd"));
			String s = (String)itemCostCache.get("171004886").getObjectValue();
			boolean ss = itemCostCache.isKeyInCache("17100886");
			System.out.println(itemCostCache.calculateInMemorySize());
			System.out.println(itemCostCache.getMemoryStoreSize());*/
    		
    	/*	orderMiningManager.dumpSellerItemsToDB(u.getId(), u.getUserId(), this.taobaoISVAppManager.getOrderAppKey(), 
    				this.taobaoISVAppManager.getOrderAppSecret(), u.getToken(), null, null);*/
    		/*TaobaoClient client=new DefaultTaobaoClient(this.taobaoISVAppManager.getTopUrl(), this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret());
    		ItemGetRequest req=new ItemGetRequest();
    		req.setFields("num_iid,title,price,skus,props_name");
    		req.setNumIid(19348645681L);
    		ItemGetResponse response = client.execute(req , u.getCurrentToken());
    		
    		
    		TradesSoldGetRequest reqs=new TradesSoldGetRequest();
    		reqs.setFields("tid,num,num_iid,status,title,type,price,point_fee,total_fee,pay_time,modified,end_time,alipay_id,alipay_no,buyer_nick,buyer_area,has_buyer_message,credit_card_fee,adjust_fee,service_orders,buyer_rate,seller_can_rate,seller_nick,payment,seller_rate,post_fee,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,consign_time,received_payment,orders");
    		Date dateTime = SimpleDateFormat.getDateTimeInstance().parse("2013-05-01 00:00:00");
    		reqs.setStartCreated(dateTime);
    		Date endTime = SimpleDateFormat.getDateTimeInstance().parse("2013-08-04 23:59:59");
    		reqs.setEndCreated(endTime);
    		
    		reqs.setPageNo(1L);
    		reqs.setPageSize(40L);
    		
    		TradesSoldGetResponse responses = client.execute(reqs , u.getCurrentToken());
    		String body = responses.getBody();
    		List<Trade> trades = responses.getTrades();
    		trades.size();*/
    		
    	/*	TaobaoClient client3=new DefaultTaobaoClient(this.taobaoISVAppManager.getTopUrl(), this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret());
    		
    		IncrementCustomerPermitRequest req3=new IncrementCustomerPermitRequest();
    		req3.setType("get,syn,notify");
    		req3.setTopics("trade;refund;item");
    		req3.setStatus("all;all;ItemAdd,ItemUpdate");
    		IncrementCustomerPermitResponse response3 = client3.execute(req3 ,  u.getCurrentToken());
    		response3.getBody();*/
    	}catch(IOException e){
    		log.error("error:",e);
    		nav.redirectToLocation(this.taobaoISVAppManager.getRedirectOrderAuth());
    	} catch (ManagerException e) {
    		log.error("error:",e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    	
    }

	private User generateAuth(String code) throws IOException, ManagerException, ApiException {
		JSONObject object = this.taobaoISVAppManager.getOrderAuthInfoByCode(code);
		Long userid = object.getLong("taobao_user_id");
		User u = getUserInfo(userid, User.Type_TAOBAO_ORDER);
		if (u == null) {
			u = new User();
			u.setUserType(User.Type_TAOBAO_ORDER);
			u.setUserId(userid);
			u.setCurrentToken(object.getString("access_token"));
			u.setToken(object.getString("access_token"));
			u.setRtoken(object.getString("refresh_token"));
			u.setUserNick(URLDecoder.decode(object.getString("taobao_user_nick"), "UTF-8"));
			supplyUserInfo(u);
			//notify授权
			this.taobaoISVAppManager.permitNotify(this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret(), u.getToken());
			storeUserInfo(u);
			//首次进入新用户默认异步为其导入前100条订单
			new InitThread(u).start();
		} else {
			u.setCurrentToken(object.getString("access_token"));
			u.setToken(object.getString("access_token"));
			u.setRtoken(object.getString("refresh_token"));
			//notify授权
			this.taobaoISVAppManager.permitNotify(this.taobaoISVAppManager.getOrderAppKey(), this.taobaoISVAppManager.getOrderAppSecret(), u.getToken());
			updateUserInfo(u);
		}
		return u;
	
	}

	

	private void generateType(Context context) {
		context.put(APP_TYPE, User.Type_TAOBAO_ORDER);
		session.setAttribute(APP_TYPE, User.Type_TAOBAO_ORDER);
	}

	class InitThread extends Thread{
		User user;
		
		public InitThread(User user) {
			super();
			this.user = user;
		}

		@Override
		public void run() {
			try {
				orderMiningManager.dumpSellerItemsToDB(user, taobaoISVAppManager.getOrderAppKey(), taobaoISVAppManager.getOrderAppSecret(),user.getToken(), null, null);
			} catch (ManagerException e) {
				log.error("InitThread error orderMiningManager.defaultDumpTradesToDB:", e);
			}
		}
	}
	
}


